using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Speed;

namespace SpeedSearch.Forms
{

    public partial class FormIndexes : Form
    {

        Config.IndexesRow rowi;
        Config.DirectoriesRow rowd;
        Config.DirectoriesRow[] rowsd;

        public FormIndexes()
        {
            InitializeComponent();
        }

        private void FormIndexes_Load(object sender, EventArgs e)
        {
            Database db = new Database();
            config = db.Db;

            this.FormClosing += new FormClosingEventHandler(FormIndexes_FormClosing);

            grdDirectories.AllowUserToAddRows = true;
            grdDirectories.AllowUserToDeleteRows = true;
            grdDirectories.EditMode = DataGridViewEditMode.EditOnEnter;

            lstIndexes.DisplayMember = "IndexName";
            config.Indexes.DefaultView.Sort = "IndexName";
            lstIndexes.DataSource = config.Indexes;
            SetControls();
        }

        void FormIndexes_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing && config.HasChanges())
            {
                if (Program.Confirm("Grava as alterações?"))
                {
                    Program.RunSafe(this, () => Save());
                }
            }
        }

        private void lstIndexes_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                SetVars();
                if (rowi != null && rowi.RowState != DataRowState.Deleted)
                {
                    rowsd = rowi.GetDirectoriesRows();
                    config.Directories.DefaultView.RowFilter = "IndexId = " + rowi.IndexId;
                    grdDirectories.DataSource = config.Directories.DefaultView;
                    config.AcceptChanges();
                    txtExtensions.DataBindings.Clear();
                    txtExtensions.DataBindings.Add(new Binding("Text", rowi, "Extensions", true, DataSourceUpdateMode.OnPropertyChanged));
                    grdDirectories.Enabled = txtExtensions.Enabled = true;
                }
                else
                {
                    grdDirectories.DataSource = null;
                    txtExtensions.DataBindings.Clear();
                    grdDirectories.Enabled = txtExtensions.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                Program.ShowError(ex);
            }
            SetControls();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Program.RunSafe(this, () =>
                {
                    Save();
                    config = Program.Db.Db;
                });
        }

        private void grdIndexes_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            if (rowi == null)
            {
                //e.Row.Cells["Extensions"].Value = Extensions.;
                //rowi = config.Indexes[e.Row.Index];
            }
            //config.AcceptChanges();
        }

        private void grdDirectories_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            Program.RunSafe(() =>
                {
                    SetVars();
                    if (e.RowIndex >= 0)
                    {
                        string colName = grdDirectories.Columns[e.ColumnIndex].Name;
                        if (colName == "ColSelDir")
                        {
                            using (var f = new FolderBrowserDialog())
                            {
                                f.ShowNewFolderButton = true;
                                if (rowd != null && Directory.Exists(rowd.Path))
                                    f.SelectedPath = rowd.Path;
                                if (f.ShowDialog() == DialogResult.OK)
                                {
                                    DirectoryInfo dir = new DirectoryInfo(f.SelectedPath);
                                    grdDirectories.CurrentRow.Cells["IndexId"].Value = rowi.IndexId;
                                    grdDirectories.CurrentRow.Cells["DirName"].Value = dir.Name;
                                    grdDirectories.CurrentRow.Cells["Path"].Value = dir.FullName;
                                    grdDirectories.CurrentCell = grdDirectories.CurrentRow.Cells[e.ColumnIndex - 1];
                                }
                            }
                        }
                        else if (colName == "ColDelRow")
                        {
                            grdDirectories.Rows.Remove(grdDirectories.CurrentRow);
                        }
                    }
                });
        }

        private void grdDirectories_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
            Program.RunSafe(() =>
                {
                    DataGridViewRow row = grdDirectories.Rows[e.RowIndex];
                    if (row != null && rowi != null && row.Index < rowi.GetDirectoriesRows().Length)
                        rowd = rowi.GetDirectoriesRows()[row.Index];
                    else
                        rowd = null;
                });
        }

        private void grdDirectories_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            Program.RunSafe(() =>
                {
                    if (rowd != null && rowi != null && rowd.IndexId != rowi.IndexId)
                        rowd.IndexId = rowi.IndexId;
                });
        }

        private void btnDirDev_Click(object sender, EventArgs e)
        {
            Program.RunSafe(this, () =>
                {
                    using (var f = new FolderBrowserDialog())
                    {
                        f.ShowNewFolderButton = true;
                        if (Directory.Exists("C:\\Dev"))
                            f.SelectedPath = "C:\\Dev";

                        if (f.ShowDialog() == DialogResult.OK)
                        {
                            IndexHelper.CreateIndexDev(Program.Db, f.SelectedPath);
                            config = Program.Db.Db;
                            config.Indexes.DefaultView.Sort = "IndexName";
                            lstIndexes.DataSource = config.Indexes;
                            config.AcceptChanges();
                        }
                    }
                });
        }

        private void btnReindexAll_Click(object sender, EventArgs e)
        {
            //if (Program.Confirm(toolTip1.GetToolTip(btnReindexAll) + "\r\n\r\nConfirma a reindexação?"))
            //{
            Program.RunSafe(this, () =>
                 {
                     Save();
                     Program.Db.Check();

                     using (var f = new Forms.FormReindex())
                         f.ShowDialog();
                 });
            //}
        }

        void SetVars()
        {
            DataRowView row = (DataRowView)lstIndexes.SelectedItem;
            if (row != null && row.Row != null && row.Row.RowState != DataRowState.Deleted)
                rowi = (Config.IndexesRow)row.Row;
            else
                rowi = null;
        }

        void Save()
        {
            config.AcceptChanges();
            Program.Db.Db = config;
            Program.Db.Check();
            Program.Db.Save();
        }

        private void btnNewIndex_Click(object sender, EventArgs e)
        {
            Program.RunSafe(this, () =>
            {
                string indexName = Program.Prompt("Nome do novo índice", "");

                if (!string.IsNullOrWhiteSpace(indexName))
                {
                    var names = (from c in config.Indexes select c.IndexName.ToUpper()).ToList();
                    indexName = indexName.Trim();
                    if (!names.Contains(indexName.ToUpper()))
                    {
                        var rowi = config.Indexes.NewIndexesRow();
                        rowi.IndexName = indexName;
                        rowi.Path = Program.GetIndexFile(rowi.IndexName);
                        rowi.DateCreated = DateTime.Now;
                        rowi.Extensions = IndexHelper.Extensions;
                        config.Indexes.AddIndexesRow(rowi);
                        config.Indexes.AcceptChanges();

                        foreach (DataRowView rv in lstIndexes.Items)
                        {
                            if (rv.Row == rowi)
                            {
                                lstIndexes.SelectedItem = rv;
                                break;
                            }
                        }
                        lstIndexes_SelectedIndexChanged(null, null);
                    }
                    else
                        throw new Exception("Já existe um índice com o nome '" + indexName + "'");
                }
            });
            SetControls();
        }

        private void btnDeleteIndex_Click(object sender, EventArgs e)
        {
            Program.RunSafe(this, () =>
            {
                if (rowi != null)
                {
                    if (Program.Confirm("Confirma a exclusão do índice '" + rowi.IndexName + "'"))
                    {
                        var dirIndex = Program.GetIndexFile(rowi.Path);
                        if (Directory.Exists(dirIndex))
                            Directory.Delete(dirIndex, true);

                        rowi.Delete();
                        rowi = null;
                        Save();
                    }
                }
            });
            SetControls();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Program.RunSafe(this, () =>
            {
                try
                {
                    if (config.HasChanges())
                    {
                        if (Program.Confirm("Grava as alterações?"))
                            Program.RunSafe(this, () => Save());
                        else
                            config.RejectChanges();

                    }
                }
                catch { }
                Close();
            });
        }

        private void grdDirectories_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            Program.RunSafe(() =>
                {
                    var col = grdDirectories.Columns[e.ColumnIndex] as DataGridViewTextBoxColumn;
                    var cellPath = grdDirectories.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    var rowView = (System.Data.DataRowView)grdDirectories.Rows[e.RowIndex].DataBoundItem;
                    if (rowView != null)
                    {
                        var row = (Config.DirectoriesRow)rowView.Row;
                        if (col != null)
                        {
                            if (col.DataPropertyName == "Path" && Conv.HasData(cellPath.Value))
                            {
                                var cellDirName = grdDirectories.Rows[e.RowIndex].Cells["DirName"];
                                if (string.IsNullOrWhiteSpace(Conv.ToString(cellDirName.Value)))
                                    cellDirName.Value = System.IO.Path.GetFileName(cellPath.Value.ToString());
                            }
                        }
                        if (rowView.IsNew && row.IndexId == 0)
                        {
                            if (row.IndexId == 0)
                                row.IndexId = rowi.IndexId;
                        }
                    }
                });
        }

        private void grdDirectories_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            for (int r = e.RowIndex; r < e.RowIndex + e.RowCount; r++)
            {
                Config.DirectoriesRow rowd = grdDirectories.Rows[r].DataBoundItem as Config.DirectoriesRow;
                if (rowd != null && rowi != null)
                {
                    if (rowd.IndexId == 0)
                        rowd.IndexId = rowi.IndexId;
                }
            }
        }

        void SetControls()
        {
            splitContainer1.Panel2.Enabled = grdDirectories.Enabled = rowi != null;
            splitContainer1.Panel2.Visible = rowi != null;
        }

    }

}
